package com.freewater.javabase.demo.network;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.Charset;

public class CharacterGenerator {

    public static void main(String[] args) throws IOException {
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        generateCharacters(bos, 100);
        final String characters = bos.toString(Charset.forName("utf-8"));
        System.out.println(characters);
    }

    /**
     * 一个简单的字符串流生成器，注意流不会被关闭
     *
     * @param out
     * @param lineLimit
     * @throws IOException
     */
    public static void generateCharacters(OutputStream out, int lineLimit) throws IOException {
        int firstPrintableCharacter = 33;
        int numberOfPrintableCharacter = 94;
        int numberOfCharactersPerLine = 72;
        int start = firstPrintableCharacter;
        byte[] line = new byte[numberOfCharactersPerLine + 2];
        int lineCount = 0;
        while (lineCount < lineLimit) {
            for (int i = start; i < start + numberOfCharactersPerLine; i++) {
                line[i - start] = (byte) ((i - firstPrintableCharacter) % numberOfPrintableCharacter + firstPrintableCharacter);
            }
            line[72] = '\r';
            line[73] = '\n';
            out.write(line);
            start = ((start + 1) - firstPrintableCharacter) % numberOfPrintableCharacter + firstPrintableCharacter;
            lineCount++;
        }
        out.flush();// 重要的一步，强制缓存区写出
    }
}